package com.stylefeng.guns.rest.modular.attent.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.stylefeng.guns.rest.common.persistence.dao.AttentUserMapper;
import com.stylefeng.guns.rest.common.persistence.model.AttentUser;
import com.stylefeng.guns.rest.common.persistence.model.Message;
import com.stylefeng.guns.rest.common.persistence.model.User;
import com.stylefeng.guns.rest.common.utils.jpush.JpushUtils;
import com.stylefeng.guns.rest.modular.attent.controller.dto.AttentUserRequest;
import com.stylefeng.guns.rest.modular.message.service.MessageService;
import com.stylefeng.guns.rest.modular.users.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by ASUS-PC on 2018/6/25.
 */
@Service
public class AttentService {

    @Autowired
    AttentUserMapper attentUserMapper;
    @Autowired
    UserService userService;
    @Autowired
    MessageService messageService;

    //添加关注
    public boolean inserAttent(AttentUserRequest request){
        AttentUser attentUser = new AttentUser();
        attentUser.setUserId(request.getUserId());
        attentUser.setAttentedUser(request.getAttentedUserId());

        //插入消息
        Message message = new Message();
        message.setType(1);
        message.setyUser(request.getAttentedUserId());
        message.setcUser(request.getUserId());
        message.setCreateTime(new Date());
        messageService.inserData(message);

        //发送极光推送通知
        User sendUser = userService.selectUserByUserId(request.getAttentedUserId());
        User zanUser = userService.selectUserByUserId(request.getUserId());//关注用户id
        JpushUtils.sendPushMessageByAlias(sendUser.getPhone(),zanUser.getNickName(),1);

        return attentUserMapper.insert(attentUser)>0?true:false;
    }

    //取消关注
    public boolean deleteAttent(AttentUserRequest request){
        List<AttentUser> lists = attentUserMapper.selectList(Condition.create().eq("attented_user",request.getAttentedUserId())
                                                                .eq("user_id",request.getUserId()));
        if(lists.size()==0){
            return false;
        }
        return attentUserMapper.delete(Condition.create().eq("attented_user",request.getAttentedUserId())
                .eq("user_id",request.getUserId()))>0?true:false;
    }
    //查询某个用户是否被关注了
    public int queryAttntByUser(int userId,int attenedUser){
        List<AttentUser> lists = attentUserMapper.selectList(Condition.create().eq("attented_user",attenedUser)
                .eq("user_id",userId));
        if(lists.size()==0){
            return 0;
        }else {
            return 1;
        }
    }

}
